package com.nsgf.library.ui.page;

import android.os.Build;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.viewpager.widget.ViewPager;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.LibraryInfo;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityTaskPlanBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.adapter.XFragmentAdapter;
import com.nsgf.library.ui.page.fragment.TaskPlanPageFragment;
import com.nsgf.library.utils.Kits;
import com.nsgf.library.utils.PublicMethodUtils;
import com.nsgf.library.utils.ToastUtils;
import com.nsgf.library.widget.prckerview.OptionsPickerView;

import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 任务计划
 */
public class TaskPlanActivity extends BaseActivity {

    StateHolder mState;

    private ActivityTaskPlanBinding mBinding;

    private AccountRequester mAccountRequester;
    private String[] mPageTitleList = new String[]{"周度任务", "月度任务", "年度任务"};

    private List<Fragment> fragmentList = new ArrayList<>();

    @Override
    protected void initViewModel() {
        mState = getActivityScopeViewModel(StateHolder.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);

    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_task_plan, BR.vm, mState)
                .addBindingParam(BR.click, new ClickProxy());
    }

    private String planId = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getLifecycle().addObserver(mAccountRequester);
        mBinding = (ActivityTaskPlanBinding) getBinding();
        calendar = Calendar.getInstance();

        mAccountRequester.taskPlanListId(UserInfo.getInstance().getProjectCode(), calendar.get(Calendar.YEAR));

        mAccountRequester.getLibraryInfo().observe(this, new Observer<ResponseStatus<LibraryInfo>>() {
            @Override
            public void onChanged(ResponseStatus<LibraryInfo> libraryInfoResponseStatus) {
                if (libraryInfoResponseStatus.getResponseCode() == 200) {
                    if (libraryInfoResponseStatus.getData().getList().size() == 0) {
                        planId = "";
                    } else
                        planId = libraryInfoResponseStatus.getData().getList().get(0).getId();
                    if (fragmentList.size() == 0) {

                        fragmentList.add(TaskPlanPageFragment.newInstance("week", planId));
                        fragmentList.add(TaskPlanPageFragment.newInstance("month", planId));
                        fragmentList.add(TaskPlanPageFragment.newInstance("year", planId));
                        XFragmentAdapter adapter = new XFragmentAdapter(TaskPlanActivity.this, getSupportFragmentManager(), fragmentList, mPageTitleList);
                        mBinding.viewPager.setAdapter(adapter);
                        mBinding.viewPager.setOffscreenPageLimit(3);

                        PublicMethodUtils.initMagicIndicator(mBinding.magicIndicator, mBinding.viewPager, mPageTitleList, TaskPlanActivity.this);

                    } else {

                        for (Fragment fragment : fragmentList) {
                            fragment.getArguments().putString("planId", planId);
                            ((TaskPlanPageFragment) fragment).search(calendar);
                        }
                    }
                }else {
                    ToastUtils.showLongToast(libraryInfoResponseStatus.getMsg());
                }

            }
        });
        currentYear = Kits.Date.getYear(calendar.getTimeInMillis());
        dataYear = currentYear;
        getTimeYMW();

        mBinding.viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                if (position == 0) {
                    mBinding.tvTaskPlanMonthBefore.setVisibility(View.VISIBLE);
                    mBinding.tvTaskPlanMonthNext.setVisibility(View.VISIBLE);
                    mBinding.tvTaskPlanWeekBefore.setVisibility(View.VISIBLE);
                    mBinding.tvTaskPlanWeekNext.setVisibility(View.VISIBLE);
                    mBinding.tvTaskPlanYearBefore.setVisibility(View.GONE);
                    mBinding.tvTaskPlanYearNext.setVisibility(View.GONE);
                } else if (position == 1) {

                    mBinding.tvTaskPlanMonthBefore.setVisibility(View.VISIBLE);
                    mBinding.tvTaskPlanMonthNext.setVisibility(View.VISIBLE);
                    mBinding.tvTaskPlanWeekBefore.setVisibility(View.GONE);
                    mBinding.tvTaskPlanWeekNext.setVisibility(View.GONE);
                    mBinding.tvTaskPlanYearBefore.setVisibility(View.GONE);
                    mBinding.tvTaskPlanYearNext.setVisibility(View.GONE);
                } else {

                    mBinding.tvTaskPlanMonthBefore.setVisibility(View.GONE);
                    mBinding.tvTaskPlanMonthNext.setVisibility(View.GONE);
                    mBinding.tvTaskPlanWeekBefore.setVisibility(View.GONE);
                    mBinding.tvTaskPlanWeekNext.setVisibility(View.GONE);
                    mBinding.tvTaskPlanYearBefore.setVisibility(View.VISIBLE);
                    mBinding.tvTaskPlanYearNext.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private Calendar calendar;

    private int year;
    private int month;
    private int week;

    private void getDatas() {

//        mAccountRequester.getRainMonitoringList(mState.searchContent.get());
    }

    private int currentYear = 0;//当前年

    private int dataYear = 0;// 数量来源年份 用户是否新的跨年判断

    private void getTimeYMW() {

        year = Kits.Date.getYear(calendar.getTimeInMillis());
        month = Kits.Date.getMonth(calendar.getTimeInMillis());
        week = Kits.Date.WeekOfMonth(calendar.getTimeInMillis());

        mState.yearMonthWeek.set(year + "年" + month + "月" + week + "周");

        if (year != dataYear) {
            dataYear = year;
            mAccountRequester.taskPlanListId(UserInfo.getInstance().getProjectCode(), calendar.get(Calendar.YEAR));
        } else {
            for (Fragment fragment : fragmentList) {
                ((TaskPlanPageFragment) fragment).search(calendar);
            }
        }
    }

    public class ClickProxy {


        @RequiresApi(api = Build.VERSION_CODES.O)
        public void screenType() {
            final ArrayList<String> monthList = new ArrayList<>();
            final ArrayList<List<String>> weekList = new ArrayList<>();

            Calendar screenType = Calendar.getInstance();
            for (int i = 0; i < 12; i++) {
                screenType.set(Calendar.MONTH, i);
                monthList.add((i + 1) + "月");
                List<String> week = new ArrayList<>();
                YearMonth yearMonth = YearMonth.of(screenType.get(Calendar.YEAR), screenType.get(Calendar.MONTH) + 1);

                // 使用TemporalAdjusters.lastInMonth()来获取月份的最后一天
                int weekCount = yearMonth.atEndOfMonth().with(java.time.temporal.TemporalAdjusters.lastInMonth(java.time.DayOfWeek.SUNDAY)).get(java.time.temporal.WeekFields.of(java.util.Locale.getDefault()).weekOfMonth());

                for (int j = 0; j < weekCount + 1; j++) {
                    week.add((j + 1) + "周");
                }
                weekList.add(week);
            }
            OptionsPickerView mOptionsPickerView = new OptionsPickerView.Builder(TaskPlanActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {

                    calendar.set(Calendar.MONTH, options1);
                    calendar.set(Calendar.DAY_OF_MONTH, 1); // 设置为该月第一天

                    // 获取该天是周几
                    int firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

                    // 获取该周的开始时间（周一）
                    calendar.add(Calendar.DAY_OF_WEEK, Calendar.MONDAY - firstDayOfWeek);

                    if (options2 > 0) {
                        long startOfFirstWeek = calendar.getTimeInMillis() + (604800000 * options2);
                        calendar.setTimeInMillis(startOfFirstWeek);
                        getTimeYMW();
                    }
                }
            }).build();
            mOptionsPickerView.setPicker(monthList, weekList);
            mOptionsPickerView.show();
        }

        public void monthBefore() {

            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
            getTimeYMW();
        }

        public void weekBefore() {

            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 7);
            getTimeYMW();
        }

        public void yearBefore() {

            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - 1);
            getTimeYMW();
        }

        public void monthNext() {

            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
            if (calendar.get(Calendar.YEAR) > currentYear) {
                calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
                ToastUtils.showLongToast("年份不能超过当前年");
            } else
                getTimeYMW();
        }

        public void weekNext() {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 7);
            if (calendar.get(Calendar.YEAR) > currentYear) {
                calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 7);
                ToastUtils.showLongToast("年份不能超过当前年");
            } else
                getTimeYMW();

        }

        public void yearNext() {
            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 1);
            if (calendar.get(Calendar.YEAR) > currentYear) {
                calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 7);
                ToastUtils.showLongToast("年份不能超过当前年");
            } else {
                getTimeYMW();

                mAccountRequester.taskPlanListId(UserInfo.getInstance().getProjectCode(), calendar.get(Calendar.YEAR));
            }

        }
    }
}
